<template>
  <div>
        <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
<!-- 添加角色按钮   -->
      <el-button type="primary" @click="addRolesDialog">添加角色</el-button>
                  <!-- 表格区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
          <!-- 展开行 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row :class="['borderBottom','vcenter', id1 === 0 ? 'borderTop':'']" v-for="(item1, id1) in scope.row.children" :key="id1">
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                  <!-- 加上图标 -->
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级图标 -->
                <el-col :span="19">
                  <el-row :class="['borderBottom','vcenter', id2 === 0 ? '' : 'borderTop']" v-for="(item2, id2) in item1.children" :key="id2">
                                      <!-- 渲染二级权限 -->
                    <el-col :span="6">
                      <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                      <!-- 加上图标 -->
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染三级权限 -->
                    <el-col :span="18">
                       <el-tag closable @close="removeRightById(scope.row,item3.id)"  type="warning" v-for="(item3, id3) in item2.children" :key="id3">{{item3.authName}}</el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column type="index" label="#" ></el-table-column>
          <el-table-column  prop="roleName" label="角色名称" ></el-table-column>
          <el-table-column  prop="roleDesc" label="角色描述"></el-table-column>
          <el-table-column label="操作" width="300px">
            <template slot-scope="scope">
              <el-button size="mini" type="primary"  icon="el-icon-edit" @click="editRolesInfo(scope.row.id)">编辑</el-button>
              <el-button  size="mini"  type="danger"  icon="el-icon-delete" @click="deleteRolesInfo(scope.row.id)">删除</el-button>
              <el-button  size="mini"  type="warning"  icon="el-icon-setting" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
            </template>
          </el-table-column>
      </el-table>
    </el-card>
        <!-- 添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRolesDialogVisible"
      width="50%" @close="closeAddRolesForm">
      <el-form :model="addRolesForm" :rules="addRolesFormRules" ref="addRolesFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRolesForm">确 定</el-button>
      </span>
    </el-dialog>
        <!-- 修改角色的对话框 -->
    <el-dialog title="修改角色信息" :visible.sync="editRolesDialogVisible"
      width="50%">
       <el-form :model="editRolesForm" :rules="editRolesFormRules" ref="editRolesFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRolesForm">确 定</el-button>
      </span>
    </el-dialog>
            <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="showSetRightsDialogVisible"
      width="50%" @close="setRightDialogClosed">
      <!-- 树形控件 -->
      <el-tree ref="treeRef" :data="rightsList" :props="treeProps"  show-checkbox
      node-key="id" :default-expand-all="true" :default-checked-keys="defKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSetRightsDialog">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 角色列表
      rolesList: [],
      // 控制添加角色的对话框显示和隐藏
      addRolesDialogVisible: false,
      // 添加角色的对话框的表单
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单的验证规则
      addRolesFormRules: {
        roleName: [
          { required: true, message: '请选择角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制修改用户的对话框显示和隐藏
      editRolesDialogVisible: false,
      // 修改用户的对话框的表单
      editRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 修改用户表单的验证规则
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请选择角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 控制分配权限的对话框
      showSetRightsDialogVisible: false,
      // 所有权限的列表
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id(数组)
      defKeys: [],
      // (当前即将分配权限的角色id)
      roleId: []
    }
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      } else {
        console.log(res)
        this.rolesList = res.data
      }
    },
    // 编辑角色按钮
    async editRolesInfo (rowId) {
      const { data: res } = await this.$http.get(`roles/${rowId}`)
      if (res.meta.status !== 200) {
        this.$message.error('查询失败')
      } else {
        this.editRolesDialogVisible = true
        this.editRolesForm = res.data
        console.log(this.editRolesForm)
      }
    },
    // 删除角色按钮
    async deleteRolesInfo (rowId) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)

      if (confirmResult === 'cancel') {
        this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(`roles/${rowId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除角色失败')
        } else {
          this.$message.success('删除角色成功')
          this.getRolesList()
        }
      }
    },
    // 点击添加用户按钮，弹出对话框
    addRolesDialog () {
      this.addRolesDialogVisible = true
    },
    // 监听添加用户对话框的关闭事件，清空表单
    closeAddRolesForm () {
      this.$refs.addRolesFormRef.resetFields()
    },
    // 提交添加用户的表单，点击确定按钮
    submitAddRolesForm () {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post('roles', this.addRolesForm)
          if (res.meta.status !== 201) {
            this.$message.error('添加失败')
          } else {
            this.$message.success('添加成功')
            this.addRolesDialogVisible = false
            this.getRolesList()
          }
        } else {
          return false
        }
      })
    },
    // 提交添加用户的表单，点击确定按钮
    submitEditRolesForm () {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(`roles/${this.editRolesForm.roleId}`,
            {
              roleName: this.editRolesForm.roleName,
              roleDesc: this.editRolesForm.roleDesc
            })
          // console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error('修改失败')
          } else {
            this.$message.success('修改成功')
            this.editRolesDialogVisible = false
            this.getRolesList()
          }
        } else {
          return false
        }
      })
    },
    // 对权限进行删除
    async removeRightById (role, rightId) {
      // 弹窗提示用户是否要删除
      const conformResult = await this.$confirm(
        '此操作将永久删除该权限，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (conformResult !== 'confirm') {
        return this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        } else {
          this.$message.success('删除成功')
          // 删除权限成功，为了避免重刷整个页面，只需要改变children的数据
          // this.getRolesList()
          // 此时返回的res就是删除之后剩下的权限
          role.children = res.data
        }
      }
    },
    // 点击分配权限按钮，显示分配权限
    async showSetRightsDialog (row) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        this.$message.error('获取权限失败')
      } else {
        this.rightsList = res.data
        // 获取三级权限的id
        this.getLeafKey(row, this.defKeys)
        this.showSetRightsDialogVisible = true
        // 保存该角色的id，为后面添加角色的权限做准备
        this.roleId = row.id
      }
    },
    // 递归函数获取角色下，所有三级权限的id
    getLeafKey (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      } else {
        node.children.forEach(item => {
          this.getLeafKey(item, arr)
        })
      }
    },
    // 监听分配权限的对话框的关闭（防止三级权限defKeys越来越多）
    setRightDialogClosed () {
      this.defKeys = []
    },
    // 分配权限对话框的确定按钮
    async submitSetRightsDialog () {
      const keysId = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 需要将数组转换为字符串
      const keysIdStr = keysId.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysIdStr })
      if (res.meta.status !== 200) {
        this.$message.error('授权失败')
      } else {
        this.getRolesList()
        this.$message.success('授权成功')
        this.showSetRightsDialogVisible = false
      }
    }
  },
  created () {
    this.getRolesList()
  }
}
</script>
<style scoped>
.el-breadcrumb{
  margin-bottom: 15px
}
.el-table{
  margin-top: 15px
}
.el-tag{
  margin: 7px;
}
.borderTop{
  border-top: 1px solid #eeeeee
}
.borderBottom{
  border-bottom: 1px solid #eeeeee
}
/* 竖直方向上垂直居中 */
.vcenter{
  display: flex;
  align-items: center;
}
</style>
